<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>DeepSeek Chat</title>
    <style>
        body {
            margin: 0;
            padding: 0;
            height: 100vh;
            display: flex;
            flex-direction: column;
        }

        #chatContainer {
            flex: 1;
            padding: 16px;
            overflow: auto; /* 确保容器自身滚动 */
            margin-bottom: 60px; /* 预留输入框高度 */
        }

        /* 输入区域改为静态定位并作为flex布局的一部分 */
        .input-area {
            background: white;
            padding: 16px;
            box-shadow: 0 -2px 8px rgba(0, 0, 0, 0.1);
            border-top: 1px solid #eee;
        }

        .thinking {
            margin-bottom: 8px;
            font-size: 0.9em;
            opacity: 0.7;
        }

        .message {
            margin: 12px 0;
            padding: 12px;
            border-radius: 8px;
        }

        .userInput {
            background: #f0f0f0;
        }

        .systemResponse {
            background: white;
            margin-top: 16px;
        }

        .thinking {
            color: #666;
            margin-bottom: 8px;
        }

        .responseContent {
            color: #333;
            white-space: pre-line;
        }
    </style>
</head>
<body>
<!-- 聊天历史容器 -->
<div id="chatContainer" class="chat-container"></div>

<!-- 输入区域 -->
<div class="input-area">
    <textarea id="messageInput" placeholder="输入您的问题...CTRL+ENTER换行，ENTER发送" rows="4"
              style="width: 100%; resize: none; margin-bottom: 8px;"></textarea>
    <button class="button" onclick="sendRequest()" style="margin-right: 8px;">发送</button>
    <button class="button" onclick="clearHistory()" style="margin-right: 8px;">清空对话</button>
    <button onclick="terminateSession()" style="margin-right: 8px;">终止对话</button>
    <!--用户标识输入框默认值为default-->
    <label for="userInput">用户标识</label><input type="text" id="userInput" placeholder="用户标识" value="default"/>
    <!-- 模型选择器 -->
    <label for="modelSelector">模型选择</label>
    <select id="modelSelector">
        <option value="deepseek-chat">DeepSeek-V3</option>
        <option value="deepseek-reasoner">DeepSeek-R1</option>
        <option value="qwen-turbo" selected>qwen-turbo</option>
        <option value="qwq-plus">qwq-plus</option>
        <option value="qwen-max">qwen-max</option>
        <option value="qwen-plus">qwen-plus</option>

    </select>
</div>

<script>
    // 输入框id为userInput的value随机给个长度为12的随机字符
    document.getElementById('userInput').value = Math.random().toString(36).substring(2, 12);

    // 键盘监听逻辑
    document.getElementById('messageInput').addEventListener('keydown', function (event) {
        if (event.key === 'Enter') {
            if (event.ctrlKey) { // Ctrl + Enter 换行
                const textarea = this;
                const start = textarea.selectionStart;
                const end = textarea.selectionEnd;
                const text = '\n';
                textarea.value = textarea.value.slice(0, start) + text + textarea.value.slice(end);
                textarea.selectionStart = textarea.selectionEnd = start + text.length;
                event.preventDefault();
            } else { // Enter 直接发送
                event.preventDefault();
                sendRequest();
            }
        }
    });
    // 开始的定时器列表
    let activeTimers = {};

    // 发送按钮
    async function sendRequest() {
        // 输入的内容
        const input = document.getElementById('messageInput');
        const content = input.value.trim();
        if (!content) return alert('请输入内容');
        input.value = '';

        // 按钮禁用逻辑
        const buttons = document.querySelectorAll('.input-area .button');
        buttons.forEach(btn => btn.disabled = true);

        // 创建新消息容器
        const messageDiv = document.createElement('div');
        messageDiv.className = 'message';

        // 创建计时器容器（放在最前面）
        const timerDiv = document.createElement('div');
        timerDiv.className = 'thinking';
        timerDiv.style.color = '#666';
        messageDiv.appendChild(timerDiv); // 先添加计时器

        // 用户输入部分
        const userDiv = document.createElement('div');
        userDiv.className = 'userInput';
        userDiv.innerHTML = `您：${content}`;
        messageDiv.appendChild(userDiv);

        // 推理内容容器
        const reasoningDiv = document.createElement('div');
        reasoningDiv.className = 'thinking';
        userDiv.insertAdjacentElement('afterend', reasoningDiv);

        // 响应内容部分
        const responseDiv = document.createElement('div');
        responseDiv.className = 'responseContent';
        messageDiv.appendChild(responseDiv);

        // 添加到历史内容容器
        const chatContainer = document.getElementById('chatContainer');
        chatContainer.appendChild(messageDiv);
        chatContainer.scrollTop = chatContainer.scrollHeight;

        // 初始化计时器
        const timerId = setInterval(() => {
            const duration = (Date.now() - startTime) / 1000;
            timerDiv.innerHTML = `实时思考中...（用时${duration.toFixed(1)}秒）`;
        }, 100);

        startTime = Date.now();
        activeTimers[messageDiv] = timerId;


        // 获取用户标识userInput
        const userInput = document.getElementById('userInput').value;
        // 获取模型选择器的值
        const modelSelector = document.getElementById('modelSelector').value;

        // POST请求参数
        const postData = {
            session: userInput,
            model: modelSelector,
            message: content
        }

        // 发送POST请求
        const response = await fetch('/deep/seek/stream', {
            method: 'POST',
            headers: {
                'Accept': 'text/event-stream',
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(postData)
        });

        // 处理服务器事件流
        const reader = response.body.getReader();
        const decoder = new TextDecoder('utf-8');
        // 全局缓冲区处理分片数据
        let buffer = '';
        while (true) {
            const {done, value} = await reader.read();
            // "finish_reason":"stop"会触发done为true
            if (done) {
                // 恢复按钮可用
                buttons.forEach(btn => btn.disabled = false);
                // 停止计时器并显示最终时间
                clearInterval(activeTimers[messageDiv]);
                const duration = (Date.now() - startTime) / 1000;
                timerDiv.innerHTML = `已深度思考（用时${duration.toFixed(1)}秒）`;
                delete activeTimers[messageDiv];
                break;
            }
            // 转换成utf-8
            let chunk = decoder.decode(value);
            // 将所有数据累积到缓冲区
            buffer += chunk;
            // 按行分割处理
            const lines = buffer.split('\n');
            buffer = lines.pop(); // 保留未完成的行
            lines.forEach(line => {
                // 跳过空行
                if (!line.trim()) return;
                // 可能是data：
                if (line.startsWith('data:')) {
                    chunk = line.slice(5).trim(); // 去除data:前缀和空格
                }
                // 处理数据
                try {
                    // data 结构 {"index":0,"delta":{"content":"我是"},"logprobs":null,"finish_reason":null}
                    // data 额外增加message 属性
                    const data = JSON.parse(chunk);
                    const delta = data.delta;
                    if (delta.content) responseDiv.innerHTML += delta.content;
                    if (delta.reasoning_content) reasoningDiv.innerHTML += delta.reasoning_content;
                    document.getElementById('chatContainer').scrollTop = document.getElementById('chatContainer').scrollHeight;
                    if (delta.message) alert(delta.message);
                } catch (e) {
                    console.error('解析错误:', chunk, "|错误原因：", e);
                }
            })
        }
        // const encodedContent = encodeURIComponent(content);
        // const eventSource = new EventSource(`/deep/seek/stream/${userInput}/${modelSelector}/${encodedContent}`);
        // //在sendRequest中将EventSource实例与消息容器messageDiv关联：
        // messageDiv.eventSource = eventSource;
        // eventSource.onmessage = function (event) {
        //     const data = event.data;
        //     if (data === "[DONE]" || event.name === "error") {
        //         // 恢复按钮可用
        //         buttons.forEach(btn => btn.disabled = false);
        //         // 停止计时器并显示最终时间
        //         clearInterval(activeTimers[messageDiv]);
        //         const duration = (Date.now() - startTime) / 1000;
        //         timerDiv.innerHTML = `已深度思考（用时${duration.toFixed(1)}秒）`;
        //         delete activeTimers[messageDiv];
        //         if (event.name === "error") {
        //             alert("服务器出错了，请稍后再试," + event.comment)
        //         }
        //         // 显式关闭连接
        //         eventSource.close();
        //         return;
        //     }
        //
        //     try {
        //         const delta = JSON.parse(data).choices[0].delta;
        //         if (delta.content) responseDiv.innerHTML += delta.content;
        //         if (delta.reasoning_content) reasoningDiv.innerHTML += delta.reasoning_content;
        //         // 滚动到底部
        //         const chatContainer = document.getElementById('chatContainer');
        //         chatContainer.scrollTop = chatContainer.scrollHeight;
        //     } catch (e) {
        //         console.error(e);
        //     }
        // };


    }

    function clearHistory() {
        document.getElementById('chatContainer').innerHTML = '';
        // 请求url路径，来清空服务端的历史记录：/clear-history/{session}
        fetch('/deep/seek/clear-history/' + document.getElementById('userInput').value, {method: 'GET'})
            .then(response => {
                if (!response.ok) {
                    throw new Error('清空历史记录失败');
                }
                return response.text();
            })
            .then(data => {
                console.log(data);
            })
            .catch(error => {
                console.error(error);
            });
    }

    // 终止对话
    function terminateSession() {
        // 按钮解禁逻辑
        const buttons = document.querySelectorAll('.input-area .button');
        buttons.forEach(btn => btn.disabled = false);
        // 遍历所有消息容器，关闭对应的EventSource
        const chatContainer = document.getElementById('chatContainer');
        const messageDivs = chatContainer.querySelectorAll('.message');
        messageDivs.forEach(div => {
            // 通过自定义属性获取对应的EventSource
            const eventSource = div.eventSource;
            if (eventSource && eventSource.readyState !== EventSource.CLOSED) {
                eventSource.close();
            }
        });

        // 清除定时器和后端会话（原有逻辑保留）
        for (const messageDiv in activeTimers) {
            if (activeTimers.hasOwnProperty(messageDiv)) {
                clearInterval(activeTimers[messageDiv]);
                delete activeTimers[messageDiv];
            }
        }

        // 调用后端终止接口
        fetch('/deep/seek/cancel/' + document.getElementById('userInput').value, {method: 'GET'})
            .then(response => {
                if (!response.ok) throw new Error('终止失败');
                console.log('会话已终止');
            })
            .catch(error => console.error(error));
    }

</script>
</body>
</html>